package com.easybuy.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.easybuy.entity.News;
import com.easybuy.entity.Product;
import com.easybuy.entity.ProductCategory;
import com.easybuy.service.NewsService;
import com.easybuy.service.ProductCategoryService;
import com.easybuy.service.ProductService;
import com.easybuy.service.impl.NewsServiceImpl;
import com.easybuy.service.impl.ProductCategoryServiceImpl;
import com.easybuy.service.impl.ProductServiceImpl;

public class HomeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private ProductCategoryService productCategoryService = new ProductCategoryServiceImpl();
	
	private ProductService productService = new ProductServiceImpl();
	
	private NewsService newsService = new NewsServiceImpl();
	
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		// 目的：一个Servlet可以处理多个请求
		String action = request.getParameter("action");
		if (action != null) {
			switch (action) {
			case "index":
				index(request,response);
				break;
			default:
				response.sendRedirect("404.jsp");
				break;
			}
		} else {
			response.sendRedirect("404.jsp");
		}
	}
	private void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//获取分类
		List<ProductCategory> listProductCategory = productCategoryService.findAll();
		
		request.setAttribute("listProductCategory", listProductCategory);
		
		//获取1级分类中的商品
		//为什么用map，方便jsp中取到 特定分类的 商品，jsp的取值方式  mapProductList[548]
		Map<Integer, List<Product>> mapProductList = new HashMap<Integer, List<Product>>();
		int currPage = 1; //第1页
		int pageSize = 6; //页面大小
		for (ProductCategory productCategory : listProductCategory) {
			if (productCategory.getType() == 1) {
				List<Product> listProduct = productService.findByCategoryId(productCategory.getId(),1,currPage,pageSize);
				
				mapProductList.put(productCategory.getId(), listProduct);
			}
		}
		
		request.setAttribute("mapProductList", mapProductList);
		
		//获取新闻
		List<News> newsList = newsService.findNews();
		
		request.setAttribute("newsList", newsList);
		
		request.getRequestDispatcher("pre/index.jsp").forward(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
